$(function() {
    var offset = 208, speed = 900, timeoutId, ease = 'easeOutExpo', fh = $('#ftop').height(),
            slider = false, topYloc, btop = $('#button_top'), scrollTop, animation = false;
    $.extend({
        bindEvents: function() {
            $('.vote span.icon').bind('click.votecsme', this.addVote);
            $('#les_sections_id').hover($.showSubMenu, function() {
                timeoutId = setTimeout($.hideSubMenu, 100);
            });
            $('#ls-submenu').hover(function() {
                if (timeoutId) {
                    clearTimeout(timeoutId);
                }
            }, $.hideSubMenu);
            $('#cncontrol').click($.animateFooter);

            if (!!$('#connection form').length) {
                $('#connection form').xvalidator({
                    tooltip: true,
                    fields: {
                        'txtlogin': {
                            label: 'Login',
                            rule: {
                                required: true
                            },
                            message: 'Merci d\'entrer votre login.'
                        },
                        'txtpassword': {
                            label: 'Password',
                            rule: {
                                required: true
                            },
                            message: 'Merci d\'entrer votre password.'
                        }
                    },
                    onSuccess: function(e) {
                        $(this).disabled();
                        $.connection($(this));
                    }
                }).xrequest({
                    url: './administration/?act=Login',
                    onSuccess: function(e) {
                        if (e) {
                            $('#connection form').enabled();
                            switch (e.header.code) {
                                case 1:
                                    $('#txtmessage').removeClass().addClass('error').html("Donn&eacute;es incorrectes!");
                                    $('#connection form').reset();
                                    $('#connection form input:first').focus();
                                    break;
                                case 4:
                                    $('#txtmessage').removeClass().addClass('ok').html("Connect&eacute; avec succ&egrave;s...");
                                    document.location = 'administration/';
                                    break;
                                default:
                                    $('#txtmessage').removeClass().addClass('error').html("Oups ! une erreur s\'est produite lors de l\'envoi.");
                                    break;
                            }
                        }
                    }
                });
            }

            /* ANNONCE */
            var ad = $('#top-ads');

            if (ad.length > 0) {
                var popupAd = $("#popup-ad");

                $('a.close', ad).click(function() {
                    ad.fadeOut();
                });

                $('a.buttonlink', ad).click(function() {
                    popupAd.xpopup('show');
                });

                popupAd.xpopup({
                    close: true,
                    closeTitle: 'Fermer la fenêtre',
                    closeEsc: true,
                    opacity: 70,
                    overlayClose: true,
                    width: 'auto'
                });

                if (!$.cookie('ad')) {
                    popupAd.xpopup('show');

                    $.cookie('ad', 1, {
                        expires: 5,
                        path: '/'
                    });
                }
            }

            /* Newsletter form validation */
            $('#frmnewsletter').xvalidator({
                tooltip: true,
                scrollingAuto: false,
                fields: {
                    'txtnom': {
                        label: 'Nom & Prénom',
                        rule: {
                            required: true
                        },
                        message: 'Merci d\'entrer votre Nom & Prénom.'
                    },
                    'txtemail': {
                        label: 'Votre e-mail',
                        rule: {
                            required: true,
                            email: true
                        },
                        message: 'Merci d\'entrer votre E-mail.'
                    }
                },
                onSuccess: function(e) {
                    $(this).disabled();
                    $(this).xrequest('start');
                }
            }).xrequest({
                url: 'querie-newsletter-section.php',
                onSuccess: function(e) {
                    if (e) {
                        $('#frmnewsletter').enabled();
                        switch (e.header.code) {
                            case 1:
                                $('#frmnewsletter input:eq(1)').select();
                                $('#msg-newletter2').xpopup('show');
                                break;
                            case 4:
                                $('#frmnewsletter').xvalidator('reset');
                                $('#msg-newletter').xpopup('show');
                                break;
                            default:
                                alert('Oups ! une erreur s\'est produite lors de l\'envoi.');
                                document.location = './';
                                break;
                        }
                    }
                },
                onError: function() {
                    alert('Oups ! une erreur s\'est produite lors de l\'envoi.');
                    document.location = './';
                }
            });

            // POPUP PARTENAIRES
            $('#linkpartfooter').click(function(e) {
                $("#popup-partenaires").xpopup('show');
            });

            $("#popup-partenaires").xpopup({
                close: true,
                closeTitle: 'Fermer la fenêtre',
                closeEsc: true,
                opacity: 70,
                overlayClose: true
            });

            $('#msg-newletter,#msg-newletter2').xpopup({
                close: true,
                closeTitle: 'Fermer la fenêtre',
                closeEsc: true,
                opacity: 70,
                overlayClose: true
            });

            $('#sliderPartenaires').codaSlider({
                dynamicTabs: true,
                crossLinking: false,
                autoHeight: false,
                dynamicArrows: false,
                dynamicTabsPosition: '#part-nav',
                panelTitleSelector: "span.title"
            });

            $('.flexslider', '#fpartenaires').flexslider({
                controlsContainer: '#fpartenaires',
                animation: "slide",
                controlNav: true,
                directionNav: true,
                keyboard: false,
                animationLoop: true,
                slideshow: true,
                pauseOnHover: true,
                slideshowSpeed: 5000
            });

            $('a', btop).click(function() {
                $.moveScroll($('body'), 600, ease);
            });

            if (!$.cookie('adm')) {
                $.cookie('adm', 0, {
                    expires: 360,
                    path: '/'
                });
            } else {
                if ($.cookie('adm') == '1') {
                    $.connectionMove(true, false);
                } else {
                    $.connectionMove(false, false);
                }
            }

            $(window).scroll($.checkScrolling);
            $.checkScrolling();

            $(document).xrequest({
                url: './administration/?act=addViewedCounter',
                type: 'GET'
            });
        },
        checkScrolling: function() {
            scrollTop = parseInt($(document).scrollTop());
            if (scrollTop > 0) {
                if (!btop.is(':visible')) {
                    btop.show();
                }
            } else {
                if (btop.is(':visible')) {
                    btop.hide();
                }
            }
        },
        connection: function() {
            $('#txtmessage').removeClass().addClass('info').html('Travail en cours...');
            $('#connection form').xrequest('start');
        },
        unbindEvents: function(s) {
            s.unbind('click.votecsme', s.addVote);
        },
        addVote: function() {
            var i = $(this).attr('xval'), n = $(this).next().find("strong");
            $.unbindEvents($(this));
            $.upVote(i, n);

            $(this).fadeOut('medium', function() {
                $(this).remove();
            });
        },
        upVote: function(i, a) {
            var c = parseInt(a.text()) + 1;
            $.post('./querie-newsletter-vote.php', {
                xi: i,
                xa: c,
                xip: _ip,
                xcache: new Date().getTime()
            });
            a.text(c);
        },
        showSubMenu: function() {
            $('#ls-submenu').show().stop().animate({
                'height': offset
            }, speed, ease);

            if (timeoutId) {
                clearTimeout(timeoutId);
            }
        },
        hideSubMenu: function() {
            timeoutId = setTimeout(function() {
                $('#ls-submenu').stop().animate({
                    'height': 0
                }, speed, ease, function() {
                    $('#ls-submenu').hide();
                });
            }, 100);
        },
        homeAnimation: function() {
            if (!!$('#actualites').length) {
                if (!$.cookie('hom')) {
                    $('#actualites').css({
                        'overflow': 'hidden',
                        'height': 0
                    }).show().delay(100).animate({
                        'height': 355
                    }, 800, ease);

                    $('#newsletter').css({
                        'overflow': 'hidden',
                        'height': 0
                    }).show().delay(500).animate({
                        'height': 262
                    }, 800, ease, function() {
                        $('#newsletter').css('overflow', 'visible');
                    });
                    $.cookie('hom', 1, {
                        expires: 360,
                        path: '/'
                    });
                }
            }
        },
        animateFooter: function() {
            var b = $('#connection').hasClass('open') ? true : false;
            $('#connection form').xvalidator('reset');
            $('#txtmessage').empty();

            $.connectionMove(b, true);
            $.cookie('adm', null);
            $.cookie('adm', b ? 1 : 0, {
                expires: 1,
                path: '/'
            });
        },
        connectionMove: function(mode, scroll) {
            var _cnn = $('#connection'), _offset, _hf;
            if (mode) {
                _cnn.removeClass('open');
                $('#cncontrol').attr('title', 'Ouvrir').removeClass('up');
                _offset = 5;
                _hf = fh;
            } else {
                _cnn.addClass('open');
                $('#cncontrol').attr('title', 'Fermer').addClass('up');
                _offset = 174;
                _hf = fh - 140;
            }

            _cnn.stop().animate({
                'height': _offset
            }, 800, ease);
            $('#ftop').stop().animate({
                'height': _hf
            }, 800, ease);

            if (scroll) {
                $.moveScroll(_cnn, 800, ease);
            }
        },
        moveScroll: function(e, speed, ease) {
            var dest = e.offset().top;
            $('html:not(:animated),body:not(:animated)').stop().animate({
                'scrollTop': dest
            }, speed, ease);
            return false;
        },
        initialize: function() {
            //            if (!!$('#actualites').length && $.cookie('hom')) {
            //                $('#actualites,#newsletter').show().addClass('show');
            //            } else if($('#actualites').length <= 0){
            //                $('#newsletter').show().addClass('show');
            //            }

            var sliderActu = $('.flexslider', '#actualites');

            if (sliderActu.length > 0) {
                $('.flexslider', '#actualites').flexslider({
                    controlsContainer: '#act-controls',
                    animation: "slide",
                    controlNav: false,
                    directionNav: true,
                    keyboard: false,
                    animationLoop: true,
                    slideshow: true,
                    pauseOnHover: true,
                    slideshowSpeed: 5000
                });
            }

            $.bindEvents();
        },
        addViewedAlbum: function(i) {
            $(document).xrequest('set', {
                data: {
                    c: i
                }
            });
            $(document).xrequest('start');
        }
    });
    $.initialize();
});